package org.springblade.tms.global.utils;

import com.alibaba.cloud.commons.lang.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

import static org.springblade.tms.global.constant.RedisConstant.DEMAND_ORDER_SERIAL_NUMBER;
import static org.springblade.tms.global.constant.RedisConstant.SHIPPING_ORDER_SERIAL_NUMBER;

/**
 * @projectName: BladeX
 * @package: org.springblade.tms.global.utils
 * @className: OrderNumUtil
 * @author: yr
 * @description: 单据号序号工具
 * @date: 2022/5/12 15:19
 */
@Component
public class OrderNumUtil {
	@Resource
	private RedisTemplate redisTemplate;
	//自增序号
	public static String addNum(String str) {
		String numStr = str.substring(str.length() - 4); //取出最后四位数字
		if (!StringUtils.isEmpty(numStr)) { //如果最后四位不是数字，抛NumberFormatException异常
			int n = numStr.length(); //取出字符串的长度
			int num = Integer.parseInt(numStr) + 1; //将该数字加一
			String added = String.valueOf(num);
			n = Math.min(n, added.length());
			//拼接字符串
			return str.subSequence(0, str.length() - n) + added;
		} else {
			throw new NumberFormatException();
		}
	}

	@Scheduled(cron = "30 59 23 * * ?")
	public void startCommonTask() {
		redisTemplate.opsForValue().getAndSet(DEMAND_ORDER_SERIAL_NUMBER,"0001");
		redisTemplate.opsForValue().getAndSet(SHIPPING_ORDER_SERIAL_NUMBER,"0001");
	}
}
